<?php
namespace Yousheng\DatabaseToolbox\Json2Migration;

use Illuminate\Console\Concerns\InteractsWithIO;
use Illuminate\Support\Str;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Finder\Finder;

class MigrationCreator {
    use InteractsWithIO;
    /**
     * Migration methods
     */
    protected $methods;
    protected $migrations;

    /**
     * Create an instance of the Migration Creator
     * 
     * @param array $methods
     * @return void
     */
    public function __construct(Array $methods) {
        $this->methods = $methods;
        $this->migrations=$this->migrations();
        $this->output = new ConsoleOutput();
    }
    private function migrations()
    {
        $migrationPath=base_path() . '/database/migrations/';
        return collect(Finder::create()->files()->in($migrationPath))
            ->values()
            ->map(fn($SplFileInfo)=>preg_replace("/\d{4}_\d{2}_\d{2}_\d{6}_/","",$SplFileInfo->getBasename()))
            ->sort()
            ->all();
    }

    public function create() {
        foreach($this->methods as $table => $methods) {
            $this->info("开始处理表".$table.":");
            $this->createMigration($table, $methods);

            // So migrations get created in order
            sleep(1);
        }
    }

    private function createMigration($table, $methods) {
        $filename="create_{$table}_table.php";
        if(in_array($filename,$this->migrations)){
            $this->error("表".$table."对应的文件：".$filename."已存在，为了安全起见，请手工删除后再执行");
            $this->line("");
        }else{
            $filename = $this->generateFileName($table);
            $name     = $this->generateName($table);
            $stub     = $this->createStub($name, $table, $methods);
            $path     = $this->getPath($filename);
            file_put_contents($path, $stub);
            $this->warn("表".$table."的迁移文件生成成功了\n");
        }
    }

    private function generateName($table) {
        return \Str::studly(
            sprintf("create_%s_table", strtolower($table))
        );
    }

    private function generateFileName($table) {
        // 2024_10_31_120022_create_posts_table

        return sprintf('%s_create_%s_table.php', date('Y_m_d_His'), strtolower($table));
    }

    private function createStub($className, $tableName, $methods) {
        $stub = $this->getStub();
        $stub = str_replace("{{migrationName}}", $className, $stub);
        $stub = str_replace("{{tableName}}", $tableName, $stub);
        $stub = str_replace("{{methods}}", implode("\n\t\t\t\t", $methods), $stub);
        return $stub;
    }

    private function getStub() {
        return file_get_contents(__DIR__ . '/stubs/migration.stub');
    }

    private function getPath($filename) {
        return base_path() . '/database/migrations/' . $filename;
    }
}